﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;

namespace RCE.K3.YGJD.Business.PlugIn.PUR.Business
{

    [HotUpdate]
    [Description("采购申请单 建议供应商")]
    public class PurRequisitionBusinessPlugIn : AbstractBillPlugIn
    {

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            if (e.Field.Key.EqualsIgnoreCase("FReqQty") || e.Field.Key.EqualsIgnoreCase("FArrivalDate"))
            {
                DynamicObject materialIdObj = this.View.Model.GetValue("FMaterialId", e.Row) as DynamicObject;
                if (materialIdObj == null)
                {
                    return;
                }
                int materialId = Convert.ToInt32(materialIdObj["Id"]);
                string sql = "/*dialect*/select top 1 t.FSUPPLIERID from T_PUR_POORDER t join T_PUR_POORDERENTRY t1 on t1.FID = t.FID " +
                    $"where t1.FMATERIALID = '{materialId.ToString()}' order by t1.FENTRYID desc";
                var dataRows = DBUtils.ExecuteDynamicObject(this.Context, sql);
                if (dataRows.Count <= 0)
                {
                    return;
                }
                this.View.Model.SetValue("FSuggestSupplierId", dataRows[0]["FSUPPLIERID"], e.Row);
            }

        }

        public override void BeforeSave(BeforeSaveEventArgs e)
        {
            base.BeforeSave(e);


            //var entityKey = "FEntity";
            //var rowCount = this.View.Model.GetEntryRowCount(entityKey);

            //for (int i = 0; i < rowCount; i++)
            //{
            //    DynamicObject materialIdObj = this.View.Model.GetValue("FMaterialId", i) as DynamicObject;
            //    if (materialIdObj == null)
            //    {
            //        continue;
            //    }
            //    int materialId = Convert.ToInt32(materialIdObj["Id"]);
            //    string sql = "/*dialect*/select top 1 t.FSUPPLIERID from T_PUR_POORDER t join T_PUR_POORDERENTRY t1 on t1.FID = t.FID " +
            //        $"where t1.FMATERIALID = '{materialId.ToString()}' order by t1.FENTRYID desc";
            //    var dataRows = DBUtils.ExecuteDynamicObject(this.Context, sql);
            //    if (dataRows.Count <= 0)
            //    {
            //        continue;
            //    }
            //    this.View.Model.SetValue("FSuggestSupplierId", dataRows[0]["FSUPPLIERID"], i);
            //    // FSuggestSupplierId
            //}
            //this.View.UpdateView(entityKey);
        }
    }
}
